const { ApiError } = require('../utils/error')
const Core = require('@alicloud/pop-core')
const tencentcloud = require('tencentcloud-sdk-nodejs')
const qiniu = require('qiniu')

class SmsService {
  constructor(config) {
    this.config = config
    this.provider = config.provider
    this.client = null
  }

  // 初始化短信服务客户端
  async initClient() {
    if (this.client) {
      return
    }

    switch (this.provider) {
      case 'aliyun':
        this.client = new Core({
          accessKeyId: this.config.accessKeyId,
          accessKeySecret: this.config.accessKeySecret,
          endpoint: 'https://dysmsapi.aliyuncs.com',
          apiVersion: '2017-05-25'
        })
        break
      case 'tencent':
        const SmsClient = tencentcloud.sms.v20210111.Client
        const clientConfig = {
          credential: {
            secretId: this.config.secretId,
            secretKey: this.config.secretKey,
          },
          region: 'ap-guangzhou',
          profile: {
            signMethod: 'HmacSHA256',
            httpProfile: {
              reqMethod: 'POST',
              reqTimeout: 30,
              endpoint: 'sms.tencentcloudapi.com',
            },
          },
        }
        this.client = new SmsClient(clientConfig)
        break
      case 'qiniu':
        const mac = new qiniu.auth.digest.Mac(this.config.accessKey, this.config.secretKey)
        const config = new qiniu.conf.Config()
        config.useHttpsDomain = true
        this.client = new qiniu.sms.message(mac, config)
        break
      default:
        throw new ApiError(400, '不支持的短信服务商')
    }
  }

  // 发送短信
  async sendSms(phoneNumber, templateParams) {
    try {
      await this.initClient()
      
      switch (this.provider) {
        case 'aliyun':
          const aliParams = {
            RegionId: 'cn-hangzhou',
            PhoneNumbers: phoneNumber,
            SignName: this.config.signName,
            TemplateCode: this.config.templateCode,
            TemplateParam: JSON.stringify(templateParams)
          }
          
          const aliRequestOption = {
            method: 'POST',
            formatParams: false
          }

          const aliResult = await this.client.request('SendSms', aliParams, aliRequestOption)
          if (aliResult.Code !== 'OK') {
            throw new Error(aliResult.Message || '发送失败')
          }
          return aliResult

        case 'tencent':
          const tencentParams = {
            SmsSdkAppId: this.config.appId,
            SignName: this.config.signContent,
            TemplateId: this.config.templateId,
            PhoneNumberSet: [phoneNumber],
            TemplateParamSet: Object.values(templateParams)
          }
          
          const tencentResult = await this.client.SendSms(tencentParams)
          const sendStatus = tencentResult.SendStatusSet[0]
          if (sendStatus.Code !== 'Ok') {
            throw new Error(sendStatus.Message || '发送失败')
          }
          return tencentResult

        case 'qiniu':
          const qiniuParams = {
            template_id: this.config.templateId,
            mobiles: [phoneNumber],
            parameters: templateParams
          }
          
          const qiniuResult = await this.client.sendMessage(qiniuParams)
          if (qiniuResult.error) {
            throw new Error(qiniuResult.error || '发送失败')
          }
          return qiniuResult
      }
    } catch (error) {
      console.error('发送短信失败:', error)
      throw new ApiError(500, '发送短信失败: ' + error.message)
    }
  }

  // 发送测试短信
  async sendTestSms() {
    // 使用测试手机号和模板参数
    const testPhone = '13800138000'
    const testParams = {
      code: '123456'
    }
    
    return this.sendSms(testPhone, testParams)
  }
}

module.exports = SmsService 